<template>
  <div class="yun-view">
    <yunCodePreview :codeType="viewData.codeType" ref="yunPreview" :code="viewData.code">
      <template #code-button>
        <el-button type="primary" @click="saveDialog=true">保存</el-button>
        <el-button  @click="goback">返回</el-button>
      </template>
    </yunCodePreview>
    <el-dialog v-model="saveDialog" :rules="rules" title="保存示例" width="40%" center>
      <el-form ref="saveForm" :model="codeForm" label-width="100px">
        <el-form-item label="示例标题" prop="title">
          <el-input type="text" v-model="codeForm.title" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="codeForm.type" placeholder="请选择类型" clearable>
            <el-option v-for="(item,index) in store.comData.typeList" :label="item.name" :value="item.id" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="示例描述">
          <el-input type="textarea" v-model="codeForm.doc" maxlength="200" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="示例图片">
          <el-upload
            class="yun-upload"
            action="#"
            :show-file-list="false"
            :auto-upload="true"
            :http-request="uploadFileFn"
          >
            <img v-if="codeForm.imgUrl" :src="codeForm.imgUrl" class="avatar" />
            <el-icon v-else  size="30" class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveDialog = false">取消</el-button>
          <el-button type="primary" @click="saveCodeToExample">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup>
import {onMounted, reactive,ref} from 'vue'
import yunCodePreview from '@/components/code/yun-code-preview.vue';
import {useRouter,useRoute} from 'vue-router'
import {useComStore} from '@/store/commonStore.js'
import {exampleSave,exampleWatch} from '@/api/example.js'
import {uploadFile} from '@/api/index.js'
let store = useComStore()
const router = useRouter()
const route = useRoute()
const goback = ()=>{
  router.go(-1)
}
onMounted(()=>{
  let id = route.query.id
  if(id){
    getExampleInfo(id)
  }
})
const getExampleInfo = async (id)=>{
  let res = await exampleWatch({id:id})
  console.log(res,"详情")
  if(res.code==200){
    viewData.code = res.data.code
    viewData.codeType = res.data.codeType
    codeForm.title = res.data.title
    codeForm.doc = res.data.doc
    codeForm.type = res.data.type__id
    codeForm.codeType = res.data.codeType
    codeForm.imgUrl = res.data.imgUrl
    codeForm.id = id 
  }
}
//代码数据
const viewData = reactive({
  codeType:"html",
  code:`<!doctype html>
  <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    </head>
    <body>
      <h3></h3>
    </body>
  </html>`
})
//保存数据弹窗
const saveDialog = ref(false)
const saveForm = ref(null)
const codeForm = reactive({
  title:"",
  doc:"",
  type:"",
  code:'',
  codeType:'html',
  imgUrl:null,
  file:null
})
const rules = reactive({
  title:[
    { required: true, message: '请输入', trigger: 'blur' },
    { min: 3, max: 20, message: "请输入3~20个字符", trigger: 'blur' },
  ],
  type:[
    { required: true, message: '请输入', trigger: 'change' },
  ]
})
const uploadFileFn=async (params)=>{
  const file = params.file 
  if(file.type!='image/png'&&file.type!='image/jpg'&&file.type!='image/jpeg'){
    ElMessage.error("请上传正确图片")
    return
  }
  if(file.size/1024/1024>2){
    ElMessage.error("最大上传2M")
    return
  }
  codeForm.imgUrl = window.URL.createObjectURL(file)
  codeForm.file = file
}
const yunPreview = ref(null)
const saveCodeToExample = async()=>{
  let formdata = new FormData()
  formdata.append('file',codeForm.file)
  let fileInfo = await uploadFile(formdata)
  if(fileInfo.code==200){
    codeForm.imgUrl = fileInfo.data.imgUrl
  }
  console.log(fileInfo)
  await saveForm.value.validate(async (valid, fields) => {
    if (valid) {
      codeForm.code = yunPreview.value.exportCode()
      codeForm.codeType = yunPreview.value.viewData.codeType
      let res = await exampleSave(codeForm)
      if(res.code==200){
        ElMessage.success("保存成功")
        saveDialog.value = false
      }
    }
  })
}
</script>
<style lang="scss" scoped>
.yun-view{
  .yun-upload{
    width:160px;
    height:160px;
    display: flex;
    align-items: center;
    justify-content: center;
    border:1px solid #dad9d9;
      img{
        max-width:160px;
        max-height:160px;
      }
    
  }
}
</style>